package com.coding.beautiful.config;

import com.coding.beautiful.util.ResTool;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import java.lang.reflect.Method;

/**
 * @author : champ
 * @version V1.0
 * @Description:
 * @date 2021年08月15日 16:19
 */
public class WrapReturunValueHandler implements HandlerMethodReturnValueHandler {

    private ResTool ok = new ResTool(null);

    private RequestResponseBodyMethodProcessor target;

    public WrapReturunValueHandler(RequestResponseBodyMethodProcessor target) {
        this.target = target;
    }

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return true;
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        Method method = (Method) returnType.getExecutable();
        Class<?> type = method.getReturnType();
        if (type.equals( Void.class )) {
            target.handleReturnValue(ok, returnType, mavContainer, webRequest);
        } else if ( type.equals( ResTool.class ) ) {
            target.handleReturnValue(returnValue, returnType, mavContainer, webRequest);
        } else {
            target.handleReturnValue(new ResTool( returnValue ), returnType, mavContainer, webRequest);
        }
    }
}
